package slxy.jiangtao.dts.service.sys;

import com.alibaba.fastjson.JSON;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import slxy.jiangtao.dts.core.common.bean.Constants;
import slxy.jiangtao.dts.core.common.service.CommonService;
import slxy.jiangtao.dts.core.util.DateUtils;
import slxy.jiangtao.dts.core.util.EmailUtil;
import slxy.jiangtao.dts.core.util.StringUtil;
import slxy.jiangtao.dts.entity.business.Email;
import slxy.jiangtao.dts.entity.business.Notice;
import slxy.jiangtao.dts.entity.business.UserEmail;
import slxy.jiangtao.dts.entity.sys.RoleMenu;
import slxy.jiangtao.dts.entity.sys.Systemconfig;
import slxy.jiangtao.dts.entity.sys.User;

import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.persistence.criteria.CriteriaBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Code must be sexy
 * Created by Jiang Tao on 2017/5/26.
 * 说明：
 */
@Service("emailService")
public class EmailService {
    @Autowired
    CommonService commonService;

    /**
     * 获取用户所有收取邮件
     */
    public List<Map> getInEmails(Integer userId) {
        String sql = "SELECT e.id,e.name,e.create_time,u.state FROM user_email u JOIN email e on u.email_id = e.id WHERE u.receiver =" + userId;
        List<Map> emailList = commonService.findListMapBySql(sql);
        return emailList;
    }

    /**
     * 获取收件箱总数
     */
    public int getInEmailsCount(Integer userId) {
        String sql = "SELECT count(*) FROM user_email u JOIN email e on u.email_id = e.id WHERE u.receiver =" + userId;
        return Integer.parseInt(commonService.getCountForJdbc(sql).toString());
    }

    /**
     * 获取用户所有发出邮件
     */
    public List<Map> getOutEmails(Integer userId) {
        String sql = "SELECT e.id,e.name,e.create_time,e.state FROM  email e  WHERE e.state!=" + Constants.EMAIL_DELETE + " and e.creator =" + userId;
        List<Map> emailList = commonService.findListMapBySql(sql);
        return emailList;
    }

    /**
     * 获取用户所有未读取邮件
     */
    public List<Map> getUnreadEmails(Integer userId) {
        String sql = "SELECT e.* FROM user_email u JOIN email e on u.email_id = e.id WHERE u.state=0 and u.receiver =" + userId;
        List<Map> emailList = commonService.findListMapBySql(sql);
        return emailList;
    }

    /**
     * 获取用户所有已读取邮件
     */
    public List<Map> getReadEmails(Integer userId) {
        String sql = "SELECT e.* FROM user_email u JOIN email e on u.email_id = e.id WHERE u.state=1 and u.receiver =" + userId;
        List<Map> emailList = commonService.findListMapBySql(sql);
        return emailList;
    }

    /**
     * 添加或修改邮件
     */
    public Integer addOrUpdate(Email email, User user) throws Exception {
        if (email.getCreator() == null) {
            email.setCreator(user.getId());
        }
        if (StringUtil.isEmpty(email.getCreateTime())) {
            email.setCreateTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
        }
        if (email.getState() == null) {
            email.setState(Constants.EMAIL_UNSEND);//设置默认为发送状态
        }
        commonService.saveOrUpdate(email);
        return email.getId();
    }

    /**
     * 删除邮件：收件人删除user_email中的记录；发送人/创建人删除时先判断，如果已发送则修改状态为3，否则删除
     */
    public void delete(Integer emailId, User user) {
        Email email = commonService.get(Email.class, emailId);
        if (user.getId() == email.getCreator()) {
            if (email.getState() == 0) {
                commonService.delete(email);
            } else if (email.getState() == 1) {
                email.setState(2);
                commonService.updateEntity(email);
            }
        } else {
            DetachedCriteria dc = DetachedCriteria.forClass(UserEmail.class);
            dc.add(Restrictions.eq("receiver", user.getId()));
            dc.add(Restrictions.eq("emailId", emailId));
            List<UserEmail> userEmails = commonService.findByDetached(dc);
            commonService.deleteAllEntitie(userEmails);
        }
    }

    /**
     * 发送邮件所有在职人员
     *
     * @param content 邮件内容
     * @param title   邮件标题
     */
    public void sendEmailToAllPerson(String content, String title, String sendtor) throws Exception {
        // 过滤img标签,不提供发送图片功能
        String regex_img = "<img.*src=(.*?)[^>]*?>";
        Pattern p_img = Pattern.compile(regex_img, Pattern.CASE_INSENSITIVE);
        Matcher m_img = p_img.matcher(content);
        content = m_img.replaceAll("");

        //获取系统邮件账号信息
        String myEmailAccount = commonService.findUniqueByProperty(Systemconfig.class, "name", "SYSTEM_EMAIL").getValue();
        String myEmailPassword = commonService.findUniqueByProperty(Systemconfig.class, "name", "EMAIL_PASSWORD").getValue();
        String myEmailSMTPHost = commonService.findUniqueByProperty(Systemconfig.class, "name", "EMAIL_SMTP_HOST").getValue();

        //获取邮件接收人列表
        String usersql = "select name,email from user where statu=0 AND  LENGTH(email)>0";
        List<Map> receiverlist = commonService.findListMapBySql(usersql);

        //发送邮件
        Session session = EmailUtil.creatSession(myEmailSMTPHost);
        MimeMessage mimeMessage = EmailUtil.createMimeMessage(session, sendtor, myEmailAccount, receiverlist, title, content);
        EmailUtil.send(session, mimeMessage, myEmailAccount, myEmailPassword);
    }

    /**
     * 发送邮件给指定用户集合
     *
     * @param content 邮件内容
     * @param title   邮件标题
     * @param userIds 接收方用户id数组集合
     * @param sendtor 发送人姓名（昵称）
     */
    public void sendEmail(String content, String title, Integer[] userIds, String sendtor) throws Exception {
        List<Map> receiverlist = new ArrayList<>();

        //获取邮件接收人列表
        String usersql = "select name,email from user where LENGTH(email)>0 and id in(";
        //如果用户为空则不查询
        if (userIds.length > 0) {
            //组织用户查询sql并查询
            for (int i = 0; i < userIds.length - 1; i++) {
                usersql += userIds[i] + ",";
            }
            usersql += userIds[userIds.length - 1] + ")";
            receiverlist = commonService.findListMapBySql(usersql);
        }

        if (receiverlist.size() > 0) {
            // 过滤img标签,不提供发送图片功能
            String regex_img = "<img.*src=(.*?)[^>]*?>";
            Pattern p_img = Pattern.compile(regex_img, Pattern.CASE_INSENSITIVE);
            Matcher m_img = p_img.matcher(content);
            content = m_img.replaceAll("");

            //获取系统邮件账号信息
            String myEmailAccount = commonService.findUniqueByProperty(Systemconfig.class, "name", "SYSTEM_EMAIL").getValue();
            String myEmailPassword = commonService.findUniqueByProperty(Systemconfig.class, "name", "EMAIL_PASSWORD").getValue();
            String myEmailSMTPHost = commonService.findUniqueByProperty(Systemconfig.class, "name", "EMAIL_SMTP_HOST").getValue();

            //发送邮件
            Session session = EmailUtil.creatSession(myEmailSMTPHost);
            MimeMessage mimeMessage = EmailUtil.createMimeMessage(session, sendtor, myEmailAccount, receiverlist, title, content);
            EmailUtil.send(session, mimeMessage, myEmailAccount, myEmailPassword);
        }
    }

    /**
     * 添加邮件发送记录到user_email表中
     * @param emailId 邮件id
     * @param receviers 接收人
     * @param sendtor 发送人id
     */
    public void insertUserEmail(Integer emailId, Integer[] receviers, Integer sendtor) throws Exception{
        for (Integer receiver:receviers){
            UserEmail userEmail = new UserEmail();
            userEmail.setState(Constants.EMAIL_UNREAD);
            userEmail.setEmailId(emailId);
            userEmail.setSendtor(sendtor);
            userEmail.setReceiver(receiver);
            commonService.save(userEmail);
        }
    }
}
